package com.ruoyi.web.controller.mstn;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.mstnExcel.ExcelUtils;
import com.ruoyi.system.constant.ProjectStatus;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.excelImport.BatchImport;
import com.ruoyi.system.domain.excelImport.ConditionImport;
import com.ruoyi.system.domain.excelImport.ProjectImport;
import com.ruoyi.system.domain.excelImport.ResultImport;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.impl.PdfServiceImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目Controller
 * 
 * @author ruoyi
 * @date 2024-07-18
 */
@RestController
@RequestMapping("/system/project")
public class MstnProjectController extends BaseController
{
    @Autowired
    private IMstnProjectService mstnProjectService;


    @Autowired
    private IMstnCustomerService mstnCustomerService;

    @Autowired
    private IMstnProjectConditionService mstnProjectConditionService;


    @Autowired
    private IMstnSchemeBatchService mstnSchemeBatchService;

    @Autowired
    private IMstnSchemeComputeService mstnSchemeComputeService;

    @Autowired
    private IMstnCatalystsService mstnCatalystsService;

    @Autowired
    private IPdfService pdfService;

    /**
     * 查询项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(MstnProject mstnProject)
    {
        startPage();
        mstnProject.setDelFlag(UserStatus.OK.getCode());
        List<MstnProject> list = mstnProjectService.selectMstnProjectList(mstnProject);
        return getDataTable(list);
    }

    /**
     * 导出项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:export')")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MstnProject mstnProject)
    {
        mstnProject.setDelFlag(UserStatus.OK.getCode());
        List<MstnProject> list = mstnProjectService.selectMstnProjectList(mstnProject);
        ExcelUtil<MstnProject> util = new ExcelUtil<MstnProject>(MstnProject.class);
        util.exportExcel(response, list, "项目数据");
    }



    /**
     * 获取项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") Long projectId)
    {
        MstnProject project = mstnProjectService.selectMstnProjectByProjectId(projectId);
        project.setConditionList(mstnProjectConditionService.selectMstnProjectConditionListByProjectId(projectId));
        return success(project);
    }

    /**
     * 新增项目
     */
    @PreAuthorize("@ss.hasPermi('system:project:add')")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MstnProject mstnProject)
    {
        if (mstnProject.getCustomerId() == null){
            if (mstnProject.getCustomerName() == null) {
                return AjaxResult.error("客户名称不能为空");
            }
            MstnCustomer searchCustomer = new MstnCustomer();
            searchCustomer.setCustomerNameEq(mstnProject.getCustomerName());
            List<MstnCustomer> customerList = mstnCustomerService.selectMstnCustomerList(searchCustomer);
            if (customerList.size() == 1){
                mstnProject.setCustomerId(customerList.get(0).getCustomerId());
            } else if (customerList.size() > 1){
                return AjaxResult.error("客户名称重复，请重新输入");
            } else {
                MstnCustomer mstnCustomer = new MstnCustomer();
                mstnCustomer.setCustomerName(mstnProject.getCustomerName());
                mstnCustomer.setCreateBy(getUsername());
                mstnCustomerService.insertMstnCustomer(mstnCustomer);
                mstnProject.setCustomerId(mstnCustomer.getCustomerId());
            }
        }
        return toAjax(mstnProjectService.insertMstnProject(mstnProject));
    }

    /**
     * 修改项目
     */
    @PreAuthorize("@ss.hasPermi('system:project:edit')")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MstnProject mstnProject)
    {
        return toAjax(mstnProjectService.updateMstnProject(mstnProject));
    }

    /**
     * 删除项目
     */
    @PreAuthorize("@ss.hasPermi('system:project:remove')")
    @Log(title = "项目", businessType = BusinessType.DELETE)
	@DeleteMapping("/{projectId}")
    public AjaxResult remove(@PathVariable Long projectId)
    {
        MstnProject mstnProject = new MstnProject();
        mstnProject.setProjectId(projectId);
        mstnProject.setDelFlag(UserStatus.DELETED.getCode());
        return toAjax(mstnProjectService.updateMstnProject(mstnProject));
    }



    /**
     * 生成方案
     */
    @PreAuthorize("@ss.hasPermi('system:scheme:add')")
    @Log(title = "生成项目方案", businessType = BusinessType.INSERT)
    @PostMapping("/generate")
    public AjaxResult generateScheme(@RequestBody MstnSchemeBatch mstnSchemeBatch)
    {
        //生成批次
        mstnSchemeBatch.setCreateBy(getUsername());
        mstnSchemeBatch.setKeyboarder(getUsername());
        mstnSchemeBatch.setProjectStatus(ProjectStatus.PROJECT_STATUS_SCHEME);
        mstnSchemeBatch.setInputTime(DateUtils.getNowDate());
        mstnSchemeBatchService.insertMstnSchemeBatch(mstnSchemeBatch);
//        //查询条件转换
//        List<MstnProjectCondition> conditionList = mstnProjectConditionService.selectMstnProjectConditionListByProjectId(mstnSchemeBatch.getProjectId());
//        List<MstnSchemeCompute> computeList = conditionList.stream().map(condition -> MstnSchemeCompute.of(mstnSchemeBatch.getBatchId(), condition)).collect(Collectors.toList());
        mstnSchemeBatch.getComputeList().forEach(compute -> {
            compute.setBatchId(mstnSchemeBatch.getBatchId());
            compute.setProjectId(mstnSchemeBatch.getProjectId());
        });
        mstnSchemeComputeService.insertMstnSchemeComputeList(mstnSchemeBatch.getComputeList());

        return success(mstnSchemeBatch.getBatchId());
    }

    /**
     * 校验方案
     */
    @PreAuthorize("@ss.hasPermi('system:scheme:edit')")
    @Log(title = "校验项目方案", businessType = BusinessType.UPDATE)
    @PutMapping("/validate")
    public AjaxResult validateScheme(@RequestBody MstnSchemeBatch mstnSchemeBatch)
    {
        if (ProjectStatus.PROJECT_STATUS_CHECK.equals(mstnSchemeBatch.getProjectStatus()) ){
            mstnSchemeBatch.setCheckBy(getUsername());
            mstnSchemeBatch.setCheckTime(DateUtils.getNowDate());

        } else if (ProjectStatus.PROJECT_STATUS_VERIFY.equals(mstnSchemeBatch.getProjectStatus())){
            mstnSchemeBatch.setVerifyBy(getUsername());
            mstnSchemeBatch.setVerifyTime(DateUtils.getNowDate());
        }
        mstnSchemeBatch.setUpdateBy(getUsername());
        return toAjax(mstnSchemeBatchService.updateMstnSchemeBatch(mstnSchemeBatch));
    }

    /**
     * 计算
     * @param mstnSchemeBatch
     */
    @PreAuthorize("@ss.hasPermi('system:scheme:edit')")
    @Log(title = "计算项目方案", businessType = BusinessType.UPDATE)
    @PostMapping("/compute")
    public AjaxResult compute(@RequestBody MstnSchemeBatch mstnSchemeBatch)
    {
        //根据计算结果查询催化剂
        mstnCatalystsService.selectMstnCatalystsByCompute(mstnSchemeBatch);
        return success();
    }



    @PreAuthorize("@ss.hasPermi('system:project:export')")
    @Log(title = "项目生成PDF", businessType = BusinessType.EXPORT)
    @PostMapping("/export/pdf")
    public void exportPdf(HttpServletResponse response, @RequestBody  MstnSchemeBatch mstnSchemeBatch)
    {
        String filePath = RuoYiConfig.getPdfPath() + mstnSchemeBatch.getProjectId() +  "/" + mstnSchemeBatch.getBatchId() + ".pdf";
        pdfService.generatePdf(filePath, mstnSchemeBatch.getBatchId());
        File file = new File(filePath);
        if (!file.exists())
        {
            logger.error("文件不存在！");
        }
        try {
            InputStream fileInputStream = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fileInputStream.available()];
            fileInputStream.read(buffer);
            fileInputStream.close();
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.trim(file.getName()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            logger.error("导出PDF失败！");
        }
    }



    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            Map<String, JSONArray> map = ExcelUtils.readFileManySheet(file);

            List<ProjectImport> projectList = ExcelUtils.getMstnBeanList(map.get("项目"), ProjectImport.class);
            List<ConditionImport> conditionList = ExcelUtils.getMstnBeanList(map.get("条件"), ConditionImport.class);
            List<BatchImport> batchList = ExcelUtils.getMstnBeanList(map.get("方案"), BatchImport.class);
            List<ResultImport> resultList = ExcelUtils.getMstnBeanList(map.get("计算"), ResultImport.class);

            MstnProject mstnProject = projectList.get(0).toProject();

            if (mstnProject.getCustomerName() == null) {
                return AjaxResult.error("客户名称不能为空");
            }
            if (conditionList.isEmpty()){
                return AjaxResult.error("条件不能为空");
            }
            if (batchList.size() != 1){
                return AjaxResult.error("方案数量不正确");
            }
            if (resultList.size() != 1){
                return AjaxResult.error("计算数量不正确");
            }


            MstnCustomer searchCustomer = new MstnCustomer();
            searchCustomer.setCustomerNameEq(mstnProject.getCustomerName());
            List<MstnCustomer> customerList = mstnCustomerService.selectMstnCustomerList(searchCustomer);
            if (customerList.size() == 1){
                mstnProject.setCustomerId(customerList.get(0).getCustomerId());
            } else if (customerList.size() > 1){
                return AjaxResult.error("客户名称重复，请重新输入");
            } else {
                MstnCustomer mstnCustomer = new MstnCustomer();
                mstnCustomer.setCustomerName(mstnProject.getCustomerName());
                mstnCustomer.setCreateBy(getUsername());
                mstnCustomerService.insertMstnCustomer(mstnCustomer);
                mstnProject.setCustomerId(mstnCustomer.getCustomerId());
            }
            mstnProjectService.insertMstnProject(mstnProject);



            return success(mstnProject);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }




}
